<?php
namespace app\supplyer\controller;

use app\member\model\AccountModel;
use app\member\model\UsersModel;
use app\supplyer\Controller;
use app\supplyer\model\SupplyerModel;
use app\supplyer\model\SupplyerWithdrawModel;
use think\Db;

/**
 * 退货信息
 */
class Finance extends Controller
{
    protected function initialize()
    {
        parent::initialize();
        $this->Model = new SupplyerWithdrawModel();
    }
	/*------------------------------------------------------ */
	//-- 首页
	/*------------------------------------------------------ */
    public function index()
    {
        $this->assign("start_date", date('Y/m/01',strtotime("-1 months")));
        $this->assign("end_date",date('Y/m/d'));
        $this->getList(true);
        $balance_money = (new SupplyerModel())->where('supplyer_id',$this->supplyer_id)->value('balance_money');
        $withdraw_money = $this->Model->where('supplyer_id',$this->supplyer_id)->where('status',0)->sum('money');
        $success_withdraw_money = $this->Model->where('supplyer_id',$this->supplyer_id)->where('status',9)->sum('money');
        $this->assign("balance_money",$balance_money);
        $this->assign("withdraw_money",$withdraw_money);
        $this->assign("success_withdraw_money",$success_withdraw_money);
        return $this->fetch('index');
    }
    /*------------------------------------------------------ */
    //-- 获取列表
    //-- $runData boolean 是否返回模板
    /*------------------------------------------------------ */
    public function getList($runData = false) {
        $this->userWithdrawType = $this->getDict('UserWithdrawType');
        $search['keyword'] = input('keyword','','trim');
        $search['status'] = input('status',0,'intval');
        $search['type'] = input('type','','trim');
        $reportrange = input('reportrange');
        $where = [];
//        if (empty($reportrange) == false){
//            $dtime = explode('-',$reportrange);
//            $where[] = ['add_time','between',[strtotime($dtime[0]),strtotime($dtime[1])+86399]];
//        }else{
//            $where[] = ['add_time','between',[strtotime("-1 months"),time()]];
//        }
//        if ($search['status'] >= 0){
//            $where[] = ['status','=',$search['status']];
//        }
//        if (empty($search['keyword']) == false){
//            $UsersModel = new UsersModel();
//            $uids = $UsersModel->where(" mobile LIKE '%".$search['keyword']."%' OR user_name LIKE '%".$search['keyword']."%' OR nick_name LIKE '%".$search['keyword']."%' OR user_id = '".$search['keyword']."'")->column('user_id');
//            $uids[] = -1;//增加这个为了以上查询为空时，限制本次主查询失效
//            $where[] = ['user_id','in',$uids];
//        }
        if (empty($search['type']) == false){
            $where[] = ['account_type','=',$search['type']];
        }
        $is_export =  input('is_export',0,'intval');
        if ($is_export > 0) {
            return $this->export($where);
        }
//        $viewObj = $this->Model->where($where);

        $sqlOrder = "add_time DESC";
        $data = $this->getPageList($this->Model,$where,'*',10,$sqlOrder);
        foreach ($data['list'] as $key=>$row){
            $row['account_info'] = json_decode($row['account_info'],true);
            $data['list'][$key] = $row;
        }
        $this->assign("status", $this->Model->status);
        $this->assign("search", $search);
        $this->assign("data", $data);
        $fee_types = config('config.fee_types');
        $this->assign('fee_types', $fee_types);
        $this->assign('withdraw_account_type', config('config.withdraw_account_type'));
        if ($runData == false){
            $data['content']= $this->fetch('list')->getContent();
            unset($data['list']);
            return $this->success('','',$data);
        }
        return true;
    }

    /*------------------------------------------------------ */
    //-- 信息页调用
    //-- $data array 自动读取对应的数据
    /*------------------------------------------------------ */
    public function asInfo($data){
        $data['account'] = json_decode($data['account_info'],true);
        $userWithdrawType = $this->getDict('UserWithdrawType');
        $data['status_name'] = $userWithdrawType[$data['status']]['name'];
        $this->assign('withdraw_account_type', config('config.withdraw_account_type'));
        $supplyer = (new SupplyerModel())->where('supplyer_id',$this->supplyer_id)->find();
        $this->assign('supplyer', $supplyer);
        return $data;
    }

    public function apply()
    {
        $money = input('money',0);
        $supplyer = (new SupplyerModel())->where('supplyer_id',$this->supplyer_id)->find();
        if($money > $supplyer['balance_money']){
            return $this->error('余额不足');
        }
        $withdraw_fee = $supplyer['withdrawal_rate'] > 0 ? round($money * ($supplyer['withdrawal_rate']/100),2) : 0;
        $account_info = [
            'bank_name' => $supplyer['bank_name'],
            'bank_subbranch' => $supplyer['bank_branch'],
            'bank_card_number' => $supplyer['bank_number'],
            'bank_user_name' => $supplyer['bank_account'],
        ];
        $ins_data = [
            'supplyer_id' => $this->supplyer_id,
            'account_type' => 'bank',
            'account_info' => json_encode($account_info),
            'money' => $money,
            'withdraw_fee' => $withdraw_fee,
            'fee_type' => 1,
            'real_money' => $money,
            'arrival_money' => $money - $withdraw_fee,
            'add_time' => time()
        ];
        Db::startTrans();//启动事务
        $r = $this->Model->insert($ins_data);
        if($r){
            $res = (new SupplyerModel())->where('supplyer_id',$this->supplyer_id)->dec('balance_money',$money)->update();
            if(!$res){
                Db::rollback();// 回滚事务
                return $this->error('扣款失败');
            }
            Db::commit();// 提交事务
            return $this->success('申请成功.','reload');
        }else{
            Db::rollback();// 回滚事务
            return $this->error('申请失败');
        }
    }
}
